package servlets;

import java.io.IOException;
import java.util.ArrayList;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import managers.ConnectionManager;
import managers.DeviceManager;

import entities.Connection;
import entities.Device;
import entities.DeviceNC;
import entities.DeviceType;

/**
 * Servlet implementation class ConnectionList
 */
@WebServlet("/ConnectionList")
public class ConnectionListServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	@EJB
	ConnectionManager cm;
	@EJB
	DeviceManager dm;
       
    public ConnectionListServlet() {
        super();
        
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ArrayList<Connection> connections = new ArrayList<Connection>();
		String uuid = request.getParameter("uuid");
		connections = (ArrayList<Connection>) cm.getConnections(uuid);
		
		//Gets the host device
		Device d = new Device();
		DeviceNC temp = dm.getDevice(uuid, false);
		d.setDeviceName(temp.getName());
		d.setIpAddress(temp.getIp());
		d.setUUID(temp.getUuid());
		d.setDeviceType(DeviceType.valueOf(temp.getType()));
		
		ArrayList<String> connectedDevices = new ArrayList<String>();
		for(Connection c : connections){
			connectedDevices.add(c.getTarget());
		}
		d.setConnectedDevices(connectedDevices);
		request.setAttribute("device", d);
		
		//Gets the possible target devices
		ArrayList<DeviceNC> targets = new ArrayList<DeviceNC>();
		for(String tuuid : d.getConnectedDevices()){
			DeviceNC tempDevice = new DeviceNC();
			tempDevice = dm.getDevice(tuuid, false);
			targets.add(tempDevice);
		}
		request.setAttribute("targetDevices", targets);
		
		request.getRequestDispatcher("/WEB-INF/ConnectionList.jsp").forward(request, response);
	}

}
